<?php
declare (strict_types = 1);
namespace app\admin\controller;

use think\Request;
use think\facade\{View};
use think\exception\ValidateException;

use app\common\model\{User, Img, UserAlbum};
use app\common\validate\{UserValidate};

class UserController extends BaseController
{
    private $userModel;
    public function __construct(User $userModel)
    {
        parent::initialize();
        $this->userModel = $userModel;
    }

    /** 渲染用户列表页面 */
    public function user_list()
    {
        return view();
    }

    /** 渲染用户详情页面 */
    public function user_show()
    {
        $data = input('');
        $imgModel   = new Img();
        $albumModel = new UserAlbum();

        $info = $this->userModel->getFind(['id' => $data['id']]);
        $album_list = $albumModel->getList(['user_id' => $data['id']], 0);

        foreach($album_list['data'] as $v){
            $v['img'] = $imgModel->getVal(['obj_id' => $v['id'], 'type' => 1], 'img')['data'];
        }

        View::assign('info', $info['data']);
        View::assign('album', $album_list['data']);
        return view();
    }

    /** 渲染用户相册图片页面 */
    public function user_album_img()
    {
        $data = input('');
        $imgModel   = new Img();

        $list = $imgModel->getList(['obj_id' => $data['id'], 'type' => 1], 0);

        View::assign('list', $list['data']);
        return view();
    }

    // 获取用户数据列表
    public function user_data()
    {
        $data = input('get.');

        try{
            validate(UserValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $where = [];

        if($data && isset($data['key'])){
            if(!empty($data['key']['phone'])){
                $where[] = ['phone', 'like', '%' . $data['key']['phone'] . '%'];
            }

            if(!empty($data['key']['nickname'])){
                $where[] = ['nickname', 'like', '%' . $data['key']['nickname'] . '%'];
            }
        }

        /** 查询数据总条数 */
        $count = $this->userModel->getNum($where)['data'];

        $list = $this->userModel->getList($where, 1, $data['page'], $data['limit']);

        if($list['code'] != 'ok'){
            $this->error_back('暂无数据~');
        }

        $this->success_back('ok', $list['data'], $count);
    }
}
